package com.geeker.framework.web.exception;

import com.geeker.common.api.CommonResult;
import com.geeker.common.exception.BusinessException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @description: TODO
 * @date 2021/8/6 14:26
 */
@Controller
@RestControllerAdvice
public class ValidParamExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> errors = bindingResult.getFieldErrors();
        //初始化错误信息大小
        String errorMessage = "";
        for (FieldError error : errors) {
            errorMessage += error.getDefaultMessage() + "，";
        }
        if (errorMessage.length() > 0)
            errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
        return CommonResult.failed(errorMessage);
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public CommonResult handleBusinessException(BusinessException ex) {
        return new CommonResult(ex.getCode(), ex.getMessage());
    }
}
